package com.hiv.service;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson.JSON;
import com.hiv.common.Constants;
import com.hiv.common.enums.ErrorCode;
import com.hiv.common.param.WechatLoginParam;
import com.hiv.common.service.RedisService;
import com.hiv.common.utils.AssertUtil;
import com.hiv.config.ConfigurationConfig;
import com.hiv.mapper.AdminMapper;
import com.hiv.mapper.RoleMapper;
import com.hiv.mapper.domain.Admin;
import com.hiv.mapper.domain.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 用户Service业务层处理
 *
 * @author zhanghong
 * @date 2022-07-10
 */
@Service
public class UserService {
    @Autowired
    private RedisService redisService;
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private HospitalService hospitalService;

    /**
     * 查询用户
     *
     * @param id 用户主键
     * @return 用户
     */
    public Admin getById(Long id) {
        Admin admin = adminMapper.selectById(id);
        if (admin != null) {
            Role role = roleMapper.findByAdminId(admin.getId());
            AssertUtil.assertNotNull(role, "非法的用户,角色不存在,联系管理员");
            admin.setRoleId(role.getId());
            admin.setWechatRoleType(role.getWechatRoleType());
            admin.setHospitalName(hospitalService.getHospitalName(admin.getHospitalId()));
        }
        return admin;
    }

    /**
     * 查询用户
     *
     * @param id 用户主键
     * @return 用户
     */
    public String getSignById(Long id) {
        Admin admin = adminMapper.selectById(id);
        if (admin != null) {
            return admin.getSignImage();
        }
        return null;
    }

    /**
     * 用户登录
     * @param param
     * @return
     */
    public String login(WechatLoginParam param) {
        Admin byAccount = adminMapper.findByAccount(param.getAccount());
        AssertUtil.assertNotNull(byAccount, "账号不存在");
        Admin loginUser = adminMapper.findByCondition(param.getAccount(), param.getPassword());
        AssertUtil.assertNotNull(loginUser, ErrorCode.USER_OR_PWD_INVALID);
        AssertUtil.assertTrue(loginUser.getStatus() == 1, "账号已被禁用，请联系管理员");
        AssertUtil.assertNull(loginUser.getType(), "非法的小程序用户");
        //判断是否是医生或者采样员
        Role role = roleMapper.findByAdminId(loginUser.getId());
        AssertUtil.assertNotNull(role, "账号无权限");
        AssertUtil.assertEqual(role.getPlatform(), 1, "账号无权限");

        // 生成token
        Map<String, Object> map = JSON.parseObject(JSON.toJSONString(loginUser), Map.class);
        String token = JWTUtil.createToken(map, ConfigurationConfig.applicationName.getBytes());
        token = SecureUtil.md5(token);
        redisService.set(String.format(Constants.LOGIN_USER_RDB_PREFIX, token), JSON.toJSONString(loginUser));
        return token;
    }
}
